<template>
  <div class="main-scroll">
    <headerc :title="title"></headerc>
    <div class="c-main-make">
      <!-- <div class="title-text">数据筛选</div> -->
      <el-card class="box-card">
      <div style="padding: 40px">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item>
            <el-input
              v-model="filterForm.deptName"
              placeholder="部门名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="query"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="reset">清除查询条件</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-button v-auth="'E01001'" type="primary" @click="goCreateDept">新建部门</el-button>
          </el-form-item>
        </el-form>
      </div>
      </el-card>
      <!-- <p style="padding: 20px">一级部门</p> -->
      <el-breadcrumb
        style="padding: 20px"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          v-for="item in breadcrumbList"
          :key="item.id"
          @click.native="goBreadcrumb(item)"
          ><a>{{ item.name }}</a></el-breadcrumb-item
        >
      </el-breadcrumb>
      <el-table :data="deptList" border :header-cell-style="{ background: '#F6F7FB' }">
        <el-table-column label="部门名称">
          <template slot-scope="scope">
            <a href="javascript:void(0);" @click="nextDept(scope.row)">{{
              scope.row.name
            }}</a>
          </template>
        </el-table-column>
        <el-table-column label="部门级别">
          <template slot-scope="{ row }">
            <p v-if="row.deptLevel == 1">一级</p>
            <p v-if="row.deptLevel == 2">二级</p>
            <p v-if="row.deptLevel == 3">三级</p>
            <p v-if="row.deptLevel == 4">四级</p>
            <p v-if="row.deptLevel == 5">五级</p>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{ row }">
            <p v-if="row.status == 1">启用</p>
            <p v-if="row.status == 2">禁用</p>
          </template>
        </el-table-column>
        <el-table-column label="成员数量">
          <template slot-scope="scope">
            <a href="javascript:void(0);" @click="goStaff(scope.row)">{{
              scope.row.members
            }}</a>
          </template>
        </el-table-column>
        <el-table-column label="主管人员">
          <template slot-scope="scope">
            <p>{{ scope.row.managerId }}</p>
          </template>
        </el-table-column>
        <!-- <el-table-column label="级别">
          <template slot-scope="scope">
            <p>{{ scope.row.updateTime }}</p>
          </template>
        </el-table-column> -->
        <el-table-column label="更新时间">
          <template slot-scope="scope">
            <p>{{ scope.row.updateTime | formatDate("yyyy-MM-dd") }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button v-auth="'E01002'" size="mini" @click="goUpdateDept(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-auth="'E01004'"
              size="mini"
              @click="goAddUser(scope.row)"
              >添加人员</el-button
            >
            <el-button
              v-auth="'E01005'"
              size="mini"
              @click="
                dialogVisible3 = true;
                proId = scope.row.id;
              "
              >设置状态</el-button
            >
            <el-button
              v-auth="'E01003'"
              size="mini"
              type="danger"
              @click="deletePosition(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      title="新建部门"
      :visible.sync="dialogVisible"
      @close="cancelCreateDept"
      width="50%"
    >
      <el-form
        ref="createDeptForm"
        :model="createDeptForm"
        :rules="deptFormRules"
        label-width="100px"
      >
        <el-form-item label="部门名称:" prop="name">
          <el-input
            v-model="createDeptForm.name"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="上级部门:">
          <el-input
            v-model="createDeptForm.parentIdList"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门级别:" prop="deptLevel">
          <el-select v-model="deptLevel" placeholder="请选择" disabled>
            <el-option
              v-for="item in deptLevelList"
              :label="item.label"
              :value="item.value"
              :key="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主管人员:">
          <el-input
            v-model="createDeptForm.managerId"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="评级:" v-if="deptLevel == 5">
          <el-select
            v-model="createDeptForm.rating"
            placeholder="请选择评级"
            @change="changeRating"
          >
            <el-option
              v-for="item in ratingList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述:">
          <el-input
            v-model="createDeptForm.description"
            type="textarea"
            :rows="4"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelCreateDept">取 消</el-button>
        <el-button v-if="!isUpdate" type="primary" @click="createDept"
          >确 定</el-button
        >
        <el-button v-if="isUpdate" type="primary" @click="updateDept"
          >编 辑</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="添加人员"
      :visible.sync="dialogVisible2"
      @close="cancel2"
      width="50%"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="部门名称:" prop="name">
          <el-input v-model="userForm.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="选择成员:" prop="emplName">
          <el-select
            filterable
            remote
            v-model="userForm.emplName"
            :remote-method="remoteMethod"
            reserve-keyword
            placeholder="请输入关键词"
            :loading="loading"
          >
            <el-option
              v-for="item in postNameOptions"
              :key="item.id"
              :label="item.emplName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel2">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="设置状态"
      :visible.sync="dialogVisible3"
      @close="cancel3"
      width="50%"
    >
      <el-form ref="statusForm" :model="statusForm" label-width="100px">
        <el-form-item label="状态选择:" prop="status">
          <el-radio-group
            v-model="statusForm.status"
            size="medium"
            @change="changeStatus"
          >
            <el-radio border label="1">启用</el-radio>
            <el-radio border label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注内容:" prop="remark">
          <el-input
            v-model="statusForm.remark"
            type="textarea"
            :rows="4"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel3">取 消</el-button>
        <el-button type="primary" @click="updateStatus">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import headerc from "@/components/header.vue";
import {
  deptList,
  createDept,
  updateDept,
  updatePro,
  getParent,
  updateUserPro,
} from "@/api/permission";
import { getlist } from "@/api";

export default {
  components: {
    headerc,
  },
  data() {
    return {
      title: "部门管理",
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      dialogVisible4: false,
      isUpdate: false,
      deptRow: "",
      proId: "",
      breadcrumbList: [{ name: "新疆中泰矿冶有限公司", id: "0" }],
      postNameOptions: [],
      ratingList: [
        {
          label: "无",
          value: 0,
        },
        {
          label: "普通",
          value: 1,
        },
        {
          label: "合格",
          value: 2,
        },
        {
          label: "达标",
          value: 3,
        },
        {
          label: "优秀",
          value: 4,
        },
        {
          label: "模范",
          value: 5,
        },
      ],
      deptLevelList: [
        {
          label: "一级",
          value: 1,
        },
        {
          label: "二级",
          value: 2,
        },
        {
          label: "三级",
          value: 3,
        },
        {
          label: "四级",
          value: 4,
        },
        {
          label: "五级",
          value: 5,
        },
      ],
      addJob: {
        jobName: "",
        description: "",
        remark: "",
      },
      addPeople: {
        jobName: "销售总监",
        choosePeople: "",
      },
      setStates: {
        chooseState: [],
        remakes: "",
      },
      statusForm: {
        status: "1",
        remake: "",
      },
      userForm: {
        name: "",
        emplName: "",
      },
      userFormRules: {
        emplName: [{ required: true, message: "请选择成员", trigger: "blur" }],
      },
      jobList: [
        {
          jobName: "班组长",
          isState: "启用",
          memberNum: "100",
          jobDes: "暂无相关描述",
          updateTime: "2016-05-02",
        },
      ],
      // pageNo: 1, // 分页页码
      // pageSize: 10, // 每页条数
      // total: 0,
      deptList: [],
      positionRow: "",
      filterForm: {
        deptName: "",
      },
      createDeptForm: {
        name: "",
        parentIdList: "新疆中泰矿冶有限公司",
        parentIdListId: ["0"],
        managerId: "",
        description: "",
      },
      rules: [],
      deptFormRules: {
        name: [{ required: true, message: "请填写部门名称", trigger: "blur" }],
      },
      positionRules: {
        postName: [
          { required: true, message: "请填写职务名称", trigger: "blur" },
        ],
      },
      parentId: "0",
      deptLevel: 1,
      loading: false,
    };
  },
  created() {
    this.getDeptList();
  },
  methods: {
    changeRating() {},
    goStaff(row) {
      this.$router.push({
        path: "/permission/staff",
        query: {
          deptId: row.id,
          deptName: row.name
        },
      });
    },
    async remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        const res = await getlist({
          emplName: query,
        });

        if (res.code == 200) {
          this.loading = false;
          this.postNameOptions = res.data;
        }
      } else {
        this.postNameOptions = [];
      }
    },
    async addUser() {
      // let params = [];
      
      // this.userForm.emplName.forEach((item,index) => {
      //   params.push({id:item,deptId:this.deptRow.id});
      // })
      // console.log(params)
      // console.log('params')
      const res = await updateUserPro([
        {
          id: this.userForm.emplName,
          positionId: this.deptRow.id,
        },
      ]);
      if (res.code == 200) {
        this.dialogVisible2 = false;
        this.$message({
          type: "success",
          message: "添加人员成功",
        });

        this.getDeptList();
      }
    },
    goAddUser(row) {
      this.dialogVisible2 = true;
      this.deptRow = row;
      this.userForm.name = row.name;
    },
    goBreadcrumb(item) {
      console.log("item", item);
      this.parentId = item.id;
      this.deptLevel = item.deptLevel + 1;
      this.createDeptForm.parentIdList = item.name;
      this.createDeptForm.parentIdListId = [item.id];
      this.getDeptList();
      if (item.deptLevel) {
        this.breadcrumbList.splice(item.deptLevel + 1);
      } else {
        this.breadcrumbList.splice(1);
      }
    },
    nextDept(row) {
      if (
        this.breadcrumbList[row.deptLevel] &&
        row.id != this.breadcrumbList[row.deptLevel].id
      ) {
        this.breadcrumbList.splice(row.deptLevel, 1, {
          name: row.name,
          id: row.id,
          deptLevel: row.deptLevel,
          parentIdList: row.parentIdList,
        });
        console.log("stap1");
        this.breadcrumbList.splice(row.deptLevel + 1);
      } else {
        if (this.breadcrumbList.length < 5) {
          this.breadcrumbList.push({
            name: row.name,
            id: row.id,
            deptLevel: row.deptLevel,
            parentIdList: row.parentIdList,
          });
          this.parentId = row.id;
          this.createDeptForm.parentIdList = row.name;
          this.createDeptForm.parentIdListId = [row.id];
          this.deptLevel = row.deptLevel + 1;
          this.getDeptList();
        }
      }
    },
    goCreateDept() {
      this.dialogVisible = true;
      this.isUpdate = false;
    },
    nextDepartment(id) {
      this.$router.push({
        path: `/permission/secondDepartment/${id}`,
      });
    },
    changeStatus(val) {
      this.statusForm.status = val;
    },
    goUpdateDept(row) {
      this.isUpdate = true;
      this.dialogVisible = true;
      this.deptRow = row;
      this.createDeptForm.name = row.name;
      this.createDeptForm.deptLevel = row.deptLevel;
      this.createDeptForm.managerId = row.managerId;
      this.createDeptForm.description = row.description;
      // this.createDeptForm.parentIdList = row.name
    },
    async updateDept() {
      this.$refs.createDeptForm.validate(async (valid) => {
        if (valid) {
          const res = await updateDept([
            {
              description: this.createDeptForm.description,
              id: this.deptRow.id,
              managerId: this.createDeptForm.managerId,
              name: this.createDeptForm.name,
              parentIdList: this.createDeptForm.parentIdListId,
              deptLevel: this.deptLevel,
            },
          ]);
          if (res.code == 200) {
            this.$refs.createDeptForm.resetFields();
            // this.createDeptForm.parentIdList = "";
            this.createDeptForm.description = "";
            this.$message({
              type: "success",
              message: "编辑成功",
            });
            this.dialogVisible = false;
            this.getDeptList();
          }
        } else {
          return false;
        }
      });
    },
    async createDept() {
      this.$refs.createDeptForm.validate(async (valid) => {
        if (valid) {
          const res = await createDept({
            description: this.createDeptForm.description,
            managerId: this.createDeptForm.managerId,
            name: this.createDeptForm.name,
            parentIdList: this.createDeptForm.parentIdListId,
            deptLevel: this.deptLevel,
          });

          if (res.code == 200) {
            this.$refs.createDeptForm.resetFields();
            // this.createDeptForm.parentIdList = "";
            this.createDeptForm.description = "";
            this.$message({
              type: "success",
              message: "创建成功",
            });
            this.dialogVisible = false;
            this.getDeptList();
          }
        } else {
          return false;
        }
      });
    },
    updateStatus(postName) {
      this.$refs.statusForm.validate(async (valid) => {
        if (valid) {
          const res = await updatePro([
            {
              id: this.proId,
              status: this.statusForm.status,
            },
          ]);
          if (res.code == 200) {
            this.dialogVisible3 = false;
            this.$message({
              type: "success",
              message: "状态设置成功",
            });
            this.getDeptList();
          }
        } else {
          return false;
        }
      });
    },
    deletePosition(id) {
      this.$confirm("是否确定删除此条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await updatePro([
            {
              id: id,
              isDeleted: "2",
            },
          ]);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getDeptList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      //  const res = await deletePosition('111')
      //  console.log("res",res)
    },
    reset() {
      this.filterForm.deptName = "";
    },
    query() {
      this.parentId = "";
      this.getDeptList();
    },
    // currentChange(pageNo) {
    //   this.pageNo = pageNo
    //   this.getDeptList()
    // },
    async getDeptList() {
      const res = await deptList({
        deptName: this.filterForm.deptName,
        isPage: false,
        pageNo: 1,
        pageSize: 5000,
        parentDeptId: this.parentId,
      });

      if (res.code == 200) {
        this.deptList = res.data.list;
        this.deptLevel = res.data.list[0].deptLevel;
        // console.log('this.deptLevel',res.data[0].deptLevel)
        // this.total = res.data.total
      }
    },
    cancelCreateDept() {
      this.dialogVisible = false;
      this.$refs.createDeptForm.resetFields();
    },
    cancel2() {
      this.dialogVisible2 = false;
      // this.$refs.addPeople.resetField();
    },
    cancel3() {
      this.dialogVisible3 = false;
      this.$refs.statusForm.resetFields();
    },
    cancel4() {
      this.dialogVisible4 = false;
    },
    setAuthority() {
      this.$router.push("jobset");
    },
    handleEdit(index, row) {
      // console.log(index, row)
    },
    handleDelete(index, row) {
      // console.log(index, row)
    },
    deleteSure() {
      this.dialogVisible4 = false;
      this.$message({
        message: "恭喜你，这是一条成功消息",
        type: "success",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
a {
  text-decoration: none;
}

.box-card {
  margin-bottom: 20px;
}

.c-main-make {
  margin-left: 35px;
  min-height: 300px;
  background: #fff;
  margin-right: 35px;
  margin-bottom: 35px;
  position: relative;
  overflow: hidden;
  border: 1px #dcdee0 solid;
}
.c-main-show {
  margin-left: 35px;
  //   min-height: 700px;
  background: #fff;
  margin-right: 35px;
  margin-bottom: 35px;
  //   position: relative;
  //   overflow: hidden;
  border: 1px #dcdee0 solid;
}
.title-text {
  width: 100%;
  height: 50px;
  border-bottom: 1px #dcdee0 solid;
  font-family: "微软雅黑 Bold", "微软雅黑 Regular", 微软雅黑, sans-serif;
  font-weight: 700;
  color: #666666;
  line-height: 50px;
  padding-left: 25px;
}
</style>
